package com.tuinui.trade;
/*
* created by kaweepapkongkittisan
*
*/




import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.tuinui.trade.entry.StockTradeDailyEntry;
import com.tuinui.trade.utility.BasedPriceExtractUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;


public class StockPriceDownloaderAppengineImpl extends BasedPriceExtractUtility implements IStockPriceDownloader{
	final public static Logger _log = LoggerFactory.getLogger(StockPriceDownloaderAppengineImpl.class);
    final public static String PATTERN_STOCK_ROW = "<tr.*?<td.*?<td.*?<td.*?<td.*?<td.*?<td.*?<td.*?<td.*?<td.*?<td.*?<td.*?<td.*?/tr>";
    final public static String PATTERN_STOCK_INDIVIDUAL = "<a href=\"stockquotation.do.*?>(.*?)</a>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>.*?<td.*?>(.*?)</td>";
    //final public static String PATTERN_STOCK_ROW = "<tr.*?/tr>";

	public String[] source;
	public StringBuffer[] content;
	
	public void downloadSource() throws Exception{
		String[] s = source;
		content = new StringBuffer[s.length];
		for(int i=0; i<s.length; i++){
			content[i] = downloadSource(s[i]);
		}
	}

	
	public StringBuffer downloadSource(String s) throws Exception{
		URL myUrl = new URL(s);

	    StringBuffer c = new StringBuffer();
        URLFetchService fetchService =
                URLFetchServiceFactory.getURLFetchService();
        FetchOptions f = FetchOptions.Builder.withDeadline((double) 360);
        HTTPRequest request = new HTTPRequest(myUrl, HTTPMethod.GET, f);
        HTTPResponse r = fetchService.fetch(request);

        c.append(new String(r.getContent(), "TIS-620"));
	    
	    //System.out.println(content.toString());
	    _log.debug("content size = " + c.length());

        _log.debug(c.toString());
	    return c;
	}

	public List<StockTradeDailyEntry> extractStockPrice() throws Exception{
		List<StockTradeDailyEntry> entries = new ArrayList<StockTradeDailyEntry>();
		
		for (int i=0; i<content.length; i++){
            _log.debug("extract price for URL #" + i);
			extractStockPrice(content[i], entries);
		}
		
		return entries;
	}
	public List<StockTradeDailyEntry> extractStockPrice(StringBuffer partialContent, List<StockTradeDailyEntry> entries) throws Exception{
		Pattern pattern = Pattern.compile(PATTERN_STOCK_ROW, Pattern.DOTALL);
		Matcher matcher = pattern.matcher(partialContent);
	    while (matcher.find()) {
	    	_log.debug("Start index: " + matcher.start());
	    	_log.debug(" End index: " + matcher.end() + " ");
	    	_log.debug(matcher.group());
	        
	        StockTradeDailyEntry entry = extractIndividualPrice(matcher.group());
	        if (entry != null){
	        	entries.add(entry);
	        }
	      }
	    
		return entries;
	}

	public StockTradeDailyEntry extractIndividualPrice(String tr) throws Exception{
		StockTradeDailyEntry entry = null;
		
		Pattern pattern = Pattern.compile(PATTERN_STOCK_INDIVIDUAL, Pattern.DOTALL);
		Matcher matcher = pattern.matcher(tr);
		if (matcher.find()){
			entry = new StockTradeDailyEntry();
			_log.debug(matcher.group(1));
			_log.debug(matcher.group(2));
			_log.debug(matcher.group(3));
			_log.debug(matcher.group(4));
			_log.debug(matcher.group(5));
			_log.debug(removeExcessTags(matcher.group(6)));
			_log.debug(removeExcessTags(matcher.group(7)));
			_log.debug(removeExcessTags(matcher.group(8)));
			_log.debug(removeExcessTags(matcher.group(9)));
			_log.debug(removeExcessTags(matcher.group(10)));
			_log.debug(removeExcessTags(matcher.group(11)));
			_log.debug(removeExcessTags(matcher.group(12)));
			
			entry.setDate(new Date());
			entry.setSymbol(leftRightTrim(matcher.group(1)));
			entry.setFlag(matcher.group(2));
			entry.setOpen(convertToNum(removeExcessTags(matcher.group(3))));
			entry.setHigh(convertToNum(removeExcessTags(matcher.group(4))));
			entry.setLow(convertToNum(removeExcessTags(matcher.group(5))));
			entry.setLast(convertToNum(removeExcessTags(matcher.group(6))));
			entry.setChange(convertToNum(removeExcessTags(matcher.group(7))));
			entry.setPercentChange(convertToNum(removeExcessTags(matcher.group(8))));
			entry.setOffer(convertToNum(removeExcessTags(matcher.group(9))));
			entry.setBid(convertToNum(removeExcessTags(matcher.group(10))));
			entry.setVolumeTrade(convertToNum(removeExcessTags(matcher.group(11))));
			entry.setValueTrade(convertToNum(removeExcessTags(matcher.group(12))));
		}
		return entry;
	}
	
	
	public String[] getSource() {
		return source;
	}

	
	public void setSource(String[] source) {
		this.source = source;
	}
	
	public String removeExcessTags(String s){
		Pattern p = Pattern.compile("<font style=\"color: (red|green);\">(.*?)</font>", Pattern.DOTALL);
		Matcher m = p.matcher(s);
		if (m.find()){
			return m.group(2);
		}else{
			return s;
		}
		
	}
	
	public static void main(String[] args)throws Exception{
		String setUrl = "http://marketdata.set.or.th/mkt/aomstocklistresult.do?tradingMethod=aomstocklistresult.do&market=SET&language=th&country=TH";
		String maiUrl = "";
		IStockPriceDownloader downloader = new StockPriceDownloaderAppengineImpl();
		downloader.setSource(new String[]{setUrl, maiUrl});
		downloader.downloadSource();
		List<StockTradeDailyEntry> tradeInfo = downloader.extractStockPrice();
		
		for (StockTradeDailyEntry e: tradeInfo){
			_log.debug("------------------------");
			_log.debug("Symbol: " + e.getSymbol());
			_log.debug("Flag: " + e.getFlag());
			_log.debug("Open: " + e.getOpen());
			_log.debug("High: " + e.getHigh());
			_log.debug("Low: " + e.getLow());
			_log.debug("Last: " + e.getLast());
			_log.debug("Change: " + e.getChange());
			_log.debug("Percent Change: " + e.getPercentChange());
			_log.debug("Offer: " + e.getOffer());
			_log.debug("Bid: " + e.getBid());
			_log.debug("Volume Trade: " + e.getVolumeTrade());
			_log.debug("Value Trade: " + e.getValueTrade());
			_log.debug("------------------------");

		}
	}

}
